<template>
  <div class="gitlab-comment-container">
    <h3>GitLab 代码评审</h3>
    
    <div class="form-section">
      <div class="input-group">
        <label>项目 ID:</label>
        <input v-model="formData.projectId" placeholder="例如: 123" />
      </div>
      
      <div class="input-group">
        <label>MR IID:</label>
        <input v-model="formData.mrIid" placeholder="例如: 456" />
      </div>
      
      <div class="input-group">
        <label>文件路径:</label>
        <input v-model="formData.filePath" placeholder="例如: src/components/HelloWorld.vue" />
      </div>
      
      <div class="input-group">
        <label>行号:</label>
        <input v-model="formData.lineNumber" type="number" placeholder="例如: 27" />
      </div>
      
      <div class="input-group">
        <label>评论内容:</label>
        <textarea v-model="formData.comment" placeholder="请输入评论内容..." rows="3"></textarea>
      </div>
      
      <button 
        @click="addInlineComment" 
        :disabled="isLoading"
        class="submit-btn"
      >
        {{ isLoading ? '提交中...' : '添加行内评论' }}
      </button>
    </div>

    <div v-if="resultMessage" :class="['result-message', resultType]">
      {{ resultMessage }}
    </div>

    <div v-if="errorDetails" class="error-details">
      <h4>错误详情:</h4>
      <pre>{{ errorDetails }}</pre>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import axios from 'axios'

const isLoading = ref(false)
const resultMessage = ref('')
const resultType = ref('')
const errorDetails = ref('')

const formData = reactive({
  projectId: '2727',
  mrIid: '78',
  filePath: 'src/views/contract/components/history.vue',
  lineNumber: '',
  comment: '',
  gitlabUrl: 'http://172.20.20.81', // 可以改为配置项
  accessToken: 'WxW99YvdqhHdJrDyQ_nw' // 建议从环境变量获取
})

const addInlineComment = async () => {
  if (!validateForm()) return

  isLoading.value = true
  resultMessage.value = ''
  errorDetails.value = ''
  
  try {
    // 1. 获取 MR 基本信息
    const mrUrl = `${formData.gitlabUrl}/api/v4/projects/${formData.projectId}/merge_requests/${formData.mrIid}?private_token=WxW99YvdqhHdJrDyQ_nw`
    const mrResponse = await axios.get(mrUrl, {
      headers: { 'PRIVATE-TOKEN': formData.accessToken }
    })
    const mrData = mrResponse.data

    // 2. 使用 Compare API 获取差异信息
    const compareUrl = `${formData.gitlabUrl}/api/v4/projects/${formData.projectId}/repository/compare?private_token=WxW99YvdqhHdJrDyQ_nw`
    const compareParams = {
      from: mrData.target_branch,
      to: mrData.source_branch,
      straight: false
    }

    const compareResponse = await axios.get(compareUrl, {
      params: compareParams,
      headers: { 'PRIVATE-TOKEN': formData.accessToken }
    })

    const compareData = compareResponse.data
    console.log('Compare API 响应:', compareData)

    // 3. 构建 position 对象
    const position = {
      base_sha: compareData.commit?.parent_ids?.[0] || mrData.diff_refs?.base_sha,
      start_sha: compareData.commit?.parent_ids?.[0] || mrData.diff_refs?.start_sha,
      head_sha: compareData.commit?.id || mrData.sha,
      position_type: 'text',
      new_path: formData.filePath,
      new_line: parseInt(formData.lineNumber),
      old_path: formData.filePath,
      old_line: null
    }
    
    // 2. 创建行内评论
    // const discussionUrl = `${formData.gitlabUrl}/api/v4/projects/${formData.projectId}/merge_requests/${formData.mrIid}/notes?private_token=WxW99YvdqhHdJrDyQ_nw`
    
    // const payload = {
    //   body: formData.comment,
    //   position:position
    // }
    
    // const discussionResponse = await axios.post(discussionUrl, payload, {
    //   headers: {
    //     'PRIVATE-TOKEN': formData.accessToken,
    //     'Content-Type': 'application/json'
    //   }
    // })
    const commitSha = mrResponse.data.sha

      const commitUrl = `${formData.gitlabUrl}/api/v4/projects/${formData.projectId}/repository/commits/${commitSha}/comments?private_token=WxW99YvdqhHdJrDyQ_nw`
      const commitPayload = {
        note: formData.comment,
        path: formData.filePath,
        line: parseInt(formData.lineNumber),
        line_type: 'new'
      }

    const response = await axios.post(commitUrl, commitPayload, {
        headers: { 'PRIVATE-TOKEN': formData.accessToken }
      })

      resultMessage.value = '✅ Commit Comments API成功！'
      resultType.value = 'success'
    // console.log('评论详情:', discussionResponse.data)
    
  } catch (error) {
    resultMessage.value = '❌ 添加评论失败'
    resultType.value = 'error'
    
    if (error.response) {
      errorDetails.value = JSON.stringify({
        status: error.response.status,
        data: error.response.data,
        url: error.config.url
      }, null, 2)
    } else {
      errorDetails.value = error.message
    }
    
    console.error('错误详情:', error)
  } finally {
    isLoading.value = false
  }
}

const validateForm = () => {
  if (!formData.projectId || !formData.mrIid || !formData.filePath || 
      !formData.lineNumber || !formData.comment) {
    resultMessage.value = '请填写所有必填字段'
    resultType.value = 'error'
    return false
  }
  return true
}
</script>

<style scoped>
.gitlab-comment-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

.form-section {
  background: #f5f5f5;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.input-group {
  margin-bottom: 15px;
}

.input-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.input-group input,
.input-group textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

.submit-btn {
  background: #007bff;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.submit-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.submit-btn:hover:not(:disabled) {
  background: #0056b3;
}

.result-message {
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 15px;
}

.result-message.success {
  background: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.result-message.error {
  background: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.error-details {
  background: #fff3cd;
  border: 1px solid #ffeaa7;
  border-radius: 4px;
  padding: 15px;
  margin-top: 15px;
}

.error-details pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  font-size: 12px;
}
</style>